package tw.edu.tku.im.maze;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import javax.net.SocketFactory;

import org.json.JSONException;

public abstract class PacketDeliverer {
   abstract RepPacket receive(BufferedReader in) throws IOException, JSONException;
   
   public void deliver(ReqPacket req, DeliveryListenerI l) throws JSONException{
      try {
         //final Socket s = new Socket("119.77.252.70", 3333);
         final Socket s = SocketFactory.getDefault().createSocket();
         //final SocketAddress remoteaddr = new InetSocketAddress("163.13.202.52", 3333);
         final SocketAddress remoteaddr = new InetSocketAddress("163.13.201.26", 3333);
         s.connect(remoteaddr, 10000);
         final BufferedReader in = 
            new BufferedReader(new InputStreamReader(s.getInputStream(),"UTF-8"));
         final PrintWriter out =
            new PrintWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"));
         out.println(req.toJSONString());
         out.flush();
         System.out.println(req.toJSONString());
         final RepPacket rep = this.receive(in);
         s.close();
         
         if (l != null) {
            l.processReply(rep);
         }
      } catch (UnknownHostException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
         if (l != null) {
            //[ timeout: TimeOutRep
            l.processReply(new TimeOutRep());
         }
      }
   }
}
